<template>
  <Dialog title="编辑" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item label="设备编码" prop="deviceCode">
        <el-select
          v-model="formData.deviceCode"
          filterable
          remote
          value-key="deviceCode"
          :remote-method="getSelectDeviceList"
          :loading="deviceLoading"
          @change="changeDevice"
        >
          <el-option
            v-for="item in deviceList"
            :key="item.deviceCode"
            :label="item.deviceCode"
            :value="item.deviceCode"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="设备名称" prop="deviceName">
        <el-input v-model="formData.deviceName" disabled />
      </el-form-item>
      <el-form-item label="设备类型" prop="dictDeviceType">
        <el-select v-model="formData.dictDeviceType" disabled class="!w-220px">
          <el-option
            v-for="dict in getIntDictOptions('dict_device_type')"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="项目名称" prop="spotCheckProjectName">
        <el-input v-model="formData.spotCheckProjectName" disabled />
      </el-form-item>
      <el-form-item label="判断基准" prop="criterion">
        <el-input v-model="formData.criterion" disabled />
      </el-form-item>
      <el-form-item label="问题描述" prop="problemDescription">
        <el-input
          v-model="formData.problemDescription"
          resize="none"
          type="textarea"
          :rows="3"
          placeholder="请输入原因分析"
        />
      </el-form-item>
      <el-form-item label="原因分析" prop="causeAnalysis">
        <el-input
          v-model="formData.causeAnalysis"
          resize="none"
          type="textarea"
          :rows="3"
          placeholder="请输入原因分析"
        />
      </el-form-item>
      <el-form-item label="处理结果" prop="processingResults">
        <el-input
          v-model="formData.processingResults"
          resize="none"
          type="textarea"
          :rows="3"
          placeholder="请输入处理结果"
        />
      </el-form-item>
      <el-form-item label="状态" prop="dictTaskStatus">
        <el-select
          v-model="formData.dictTaskStatus"
          placeholder="请选择状态"
          clearable
          class="!w-220px"
        >
          <el-option
            v-for="dict in getIntDictOptions('dict_task_status')"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
   import { getIntDictOptions } from '@/utils/dict'
   import * as DeviceCheckTaskApi from '@/api/produce/deviceManagement/deviceCheckTask'
   import * as ComponentApi from '@/api/componentApi/index'
   const { t } = useI18n() // 国际化
   const message = useMessage() // 消息弹窗

   const dialogVisible = ref(false) // 弹窗的是否展示
   const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
   const formData = ref({
     produceDeviceMaintenanceTaskId: undefined,
     deviceCode: undefined,
     deviceName: undefined,
     dictDeviceType: undefined,
     spotCheckProjectNumber: undefined,
     spotCheckProjectName: undefined,
     criterion: undefined,
     problemDescription: undefined,
     causeAnalysis: undefined,
     processingResults: undefined,
     dictTaskStatus: undefined
   })
   const formRules = reactive({
     deviceCode: [{ required: true, message: '设备编号不能为空', trigger: 'change' }],
     problemDescription: [{ required: true, message: '问题描述不能为空', trigger: 'blur' }],
     dictTaskStatus: [{ required: true, message: '状态不能为空', trigger: 'change' }]
   })
   const formRef = ref() // 表单 Ref

   /** 打开弹窗 */
   const open = async (id: number) => {
     dialogVisible.value = true
     resetForm()
     formLoading.value = true
     try {
       formData.value = await DeviceCheckTaskApi.getDeviceCheckTask(id)
     } finally {
       formLoading.value = false
     }
   }
   defineExpose({ open }) // 提供 open 方法，用于打开弹窗

   /**设备编码修改 */
   const changeDevice = (code) => {
     const data = deviceList.value.filter((item) => item.deviceCode == code)
     formData.value.deviceName = data[0].deviceName
     formData.value.dictDeviceType = data[0].dictDeviceType
   }
   //获取设备编码
   const deviceList = ref([])
   const deviceLoading = ref(false)
   const getSelectDeviceList = async (keyword: string) => {
     if (keyword) {
       deviceLoading.value = true
       try {
         deviceList.value = await ComponentApi.getDeviceList(keyword)
       } finally {
         deviceLoading.value = false
       }
     }
   }
   /** 提交表单 */
   const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
   const submitForm = async () => {
     // 校验表单
     if (!formRef) return
     const valid = await formRef.value.validate()
     if (!valid) return
     // 提交请求
     formLoading.value = true
     try {
       const data = formData.value as unknown as DeviceCheckTaskApi.DeviceCheckTaskVO
       await DeviceCheckTaskApi.updateDeviceCheckTask(data)
       message.success(t('common.updateSuccess'))
       dialogVisible.value = false
       // 发送操作成功的事件
       emit('success')
     } finally {
       formLoading.value = false
     }
   }

   /** 重置表单 */
   const resetForm = () => {
     formData.value = {
       produceDeviceMaintenanceTaskId: undefined,
       deviceCode: undefined,
       deviceName: undefined,
       dictDeviceType: undefined,
       spotCheckProjectNumber: undefined,
       spotCheckProjectName: undefined,
       criterion: undefined,
       problemDescription: undefined,
       causeAnalysis: undefined,
       processingResults: undefined,
       dictTaskStatus: undefined
     }
     formRef.value?.resetFields()
   }
</script>
